//
//  APPublishWorksViewController.m
//  AqualPolo
//
//  Created by dong on 2024/5/12.
//

#import "APPublishWorksViewController.h"
#import "APPublishWorksNaviBar.h"
#import "APPlaceHolderTextView.h"
#import "APPublishWorksImageCell.h"
#import "TZImagePickerController.h"
#import "NSString+Category.h"
#import "APLoginManager.h"
#import "APWorksModel.h"
#import "APDiscoveryDataManager.h"
#import "BaseDataManager.h"
#import "APHomeDataManager.h"

@interface APPublishWorksViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate>
@property (nonatomic, strong) APPublishWorksNaviBar *publishBar;
@property (nonatomic, strong) UITextField *titleTextField;
@property (nonatomic, strong) APPlaceHolderTextView *textView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *images;

@end

@implementation APPublishWorksViewController

- (NSMutableArray *)images{
    if (!_images) {
        _images = [NSMutableArray array];
    }
    return _images;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(24, 20, 20, 20);
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = UIColor.clearColor;
        [_collectionView registerClass:[APPublishWorksImageCell class] forCellWithReuseIdentifier:@"image"];
        [_collectionView registerClass:[APPublishWorksAddImageCell class] forCellWithReuseIdentifier:@"add"];
    }
    return _collectionView;
}

- (APPublishWorksNaviBar *)publishBar{
    if (!_publishBar) {
        _publishBar = [[APPublishWorksNaviBar alloc] init];
        [_publishBar.backButton addTarget:self action:@selector(backButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        [_publishBar.publishButton addTarget:self action:@selector(publishButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _publishBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadBackground:@"publish_bg"];
    [self initUI];
}


- (void)publishButtonDidClick:(UIButton *)sender{
    NSString *title = self.titleTextField.text;
    NSString *content = self.textView.textView.text;
    if ([title ap_isNullString] || [content ap_isNullString] || self.images.count == 0) {
        [self.view ShowProgressOnlyLabel:@"Images and selected labels are required！"];
        return;
    }
    [self.view ShowProgress];
    APUserModel *userModel = [[APLoginManager shareInstance] userInfo];
    APWorksModel *worksModel = [[APWorksModel alloc] init];
    worksModel.userId = userModel.userId;
    worksModel.avatar = userModel.avatarUrl;
    worksModel.nickname = userModel.nickname;
    worksModel.isCreate = YES;
    worksModel.content = content;
    worksModel.title = title;
    worksModel.isBlock = NO;
    NSMutableArray *imageNames = [NSMutableArray array];
    int index = 0;
    for (UIImage *image in self.images) {
        NSString *imageName = [BaseDataManager saveImageWithData:image toFile:images_path imageName:[NSString stringWithFormat:@"%d",index]];
        [imageNames addObject:imageName];
        index++;
    }
    worksModel.cover = imageNames.firstObject;
    worksModel.images = imageNames;
    
    [[APDiscoveryDataManager shareInstance] addWorksData:worksModel];
    WS(ws);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.navigationController != nil) {
            [ws.navigationController popViewControllerAnimated:true];
            if (ws.publishCallBack) {
                ws.publishCallBack(true, nil);
            }
        }else{
            [ws dismissViewControllerAnimated:false completion:^{
                if (ws.publishCallBack) {
                    ws.publishCallBack(true, nil);
                }
            }];
        }
    });
}



- (void)addImage{
    if (![APAuthorizationManager isCanUsePhotos]) {
        [self.view ShowProgressOnlyLabel:@"You have not authorised this permission."];
        return;
    }
    NSInteger maxCount = 9 - self.images.count;
    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCount delegate:self];
    imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
    imagePicker.preferredLanguage = @"en";
    imagePicker.allowTakeVideo = false;
    imagePicker.allowPickingVideo = false;
    [self presentViewController:imagePicker animated:true completion:nil];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    [self.images addObjectsFromArray:photos];
    [self.collectionView reloadData];
}

- (void)backButtonDidClick:(UIButton *)sender{
    if (self.navigationController != nil) {
        [self.navigationController popViewControllerAnimated:true];
    }else{
        [self dismissViewControllerAnimated:true completion:nil];
    }
}

- (void)deleteButtonDidClick:(UIButton *)sender{
    CGPoint point = sender.center;
    point = [self.collectionView convertPoint:point fromView:sender.superview];
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    [self.images removeObjectAtIndex:indexPath.item];
    [self.collectionView reloadData];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.images.count >= 9) {
        return 9;
    }
    return self.images.count + 1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (collectionView.frame.size.width - 60) / 3;
    return CGSizeMake(width, 1.1 * width);
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.images.count > indexPath.item) {
        APPublishWorksImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"image" forIndexPath:indexPath];
        [cell.deleteButton addTarget:self action:@selector(deleteButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
        cell.imageView.image = self.images[indexPath.item];
        return cell;
    }
    APPublishWorksAddImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"add" forIndexPath:indexPath];
    
    return cell;

}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item == self.images.count) {
        [self addImage];
    }
    
}

- (void)initUI{
    [self.view addSubview:self.publishBar];
    [self.publishBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view);
    }];
    
    _titleTextField = [[UITextField alloc] init];
    _titleTextField.borderStyle = UITextBorderStyleNone;
    _titleTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Enter your title: " attributes:@{NSForegroundColorAttributeName:LYRGBAColor(255, 255, 255, 0.6),NSFontAttributeName:[LYFont fontWithSize:20 fontName:LYFontNamepfr]}];
    _titleTextField.font = [LYFont fontWithSize:20 fontName:LYFontNamepfr];
    _titleTextField.textColor = UIColor.whiteColor;
    [self.view addSubview:_titleTextField];
    [_titleTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.publishBar.mas_bottom);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(50);
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = LYRGBColor(129, 130, 140);
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleTextField.mas_bottom).offset(8);
        make.left.right.equalTo(_titleTextField);
        make.height.mas_equalTo(0.5);
    }];
    
    _textView = [[APPlaceHolderTextView alloc] init];
    _textView.placeHolderColor = LYRGBAColor(255, 255, 255, 0.5);
    _textView.placeHolderFont = [LYFont fontWithSize:12 fontName:LYFontNamepfr];
    _textView.placeHolder = @"Start creating your ideas.....";
    _textView.textColor = UIColor.whiteColor;
    _textView.backgroundColor = LYRGBColor(18, 23, 78);
    _textView.layer.cornerRadius = 12;
    _textView.layer.masksToBounds = true;
    [self.view addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(line.mas_bottom).offset(18);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.height.mas_equalTo(231);
    }];
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_textView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.modalPresentationStyle = UIModalPresentationFullScreen;
        self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

    }
    return self;
}

@end
